<?php

namespace app\admin\controller;

use app\admin\model\user;
use think\Controller;
use think\Db;
use think\Request;

class Login extends Controller
{
    public function login()
    {
        if (session('id') && session('account')) {
            $this->redirect(url('/admin/index/index'));
        } else {
            if (request()->isPost()) {
                $input = request()->param();

                $token = $input['__token__'];
                $account = $input['login_account'];
                $password = $input['login_password'];
                $code = $input['login_code'];

                if (checkToken($token)) {
                    if (empty($account)) adminReturn(3, '请输入账号');
                    if (empty($password)) adminReturn(3, '请输入密码');
                    if (empty($code)) adminReturn(3, '请输入验证码');
                    if (!captcha_check($code)) adminReturn(3, '验证码错误');

                    $where['account'] = $account;
                    $admin = model('user')->getAdminByUsername($where);
                    if ($admin) {
                        // 检查密码
                        if (thinkEncrypt($password) != $admin->password) adminReturn(3, '密码错误');
                        // 检查状态
                        if ($admin->status == 2) adminReturn(3, '用户被禁用，请联系管理员');

                        // 登录成功

                        //记录session
                        session('id', $admin['id']);
                        session('account', $admin['account']);

                        //记录日志
                        $log_data = [
                            'user_id' => $admin['id'],
                            'username' => $account,
                            'ip' => $_SERVER['REMOTE_ADDR'],
                            'create_time' => time()
                        ];
                        Db::name('login_log')->insert($log_data);

                        adminReturn(1, '登录成功', ['/admin/index/index']);
                    } else {
                        adminReturn(3, '登录失败');
                    }
                } else {
                    adminReturn(3, '系统繁忙，请稍后再试~');
                }
            } else {
                return $this->fetch();
            }
        }
    }
}
